<template>
  <div class="register-container">
    <el-card class="register-box">
      <div class="register-header">
        <h2>注册账号</h2>
      </div>

      <!-- 身份选择 -->
      <div class="user-type-selector">
        <el-radio-group v-model="userType" @change="handleUserTypeChange">
          <el-radio-button lable="jobseeker" class="user-type-button">
            <div class="user-type-content">
              <el-icon class="user-type-icon"><User /></el-icon>
              <h3>求职者</h3>
            </div>
          </el-radio-button>
          <el-radio-button lable="company" class="user-type-button">
            <div class="user-type-content">
              <el-icon class="user-type-icon"><OfficeBuilding /></el-icon>
              <h3>企业</h3>
            </div>
          </el-radio-button>
        </el-radio-group>
      </div>

      <p class="user-type-description">
        {{ userType === 'jobseeker' ? '选择求职者身份，开启您的求职之旅' : '选择企业身份，寻找优秀人才' }}
      </p>

      <!-- 求职者表单 -->
      <el-form
        v-if="userType === 'jobseeker'"
        ref="jobseekerFormRef"
        :model="jobseekerForm"
        :rules="jobseekerRules"
        @submit.prevent="handleSubmit"
        label-position="top"
        class="register-form"
      >
        <div class="form-section">
          <div class="form-group">
            <h4 class="form-section-title">账号信息</h4>
            <div class="form-row">
              <el-form-item label="用户名" prop="username" class="form-field">
                <el-input v-model="jobseekerForm.username" />
              </el-form-item>
              <el-form-item label="昵称" prop="nickname" class="form-field">
                <el-input v-model="jobseekerForm.nickname" />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="密码" prop="password" class="form-field">
                <el-input
                  v-model="jobseekerForm.password"
                  show-password
                  type="password"
                />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword" class="form-field">
                <el-input
                  v-model="jobseekerForm.confirmPassword"
                  show-password
                  type="password"
                />
              </el-form-item>
            </div>
          </div>

          <div class="form-group">
            <h4 class="form-section-title">个人信息</h4>
            <div class="form-row">
              <el-form-item
                label="真实姓名"
                prop="realName"
                class="form-field"
              >
                <el-input v-model="jobseekerForm.realName">
                  <template #append>
                    <el-tooltip content="仅在与企业私聊时可见" placement="top">
                      <el-icon><InfoFilled /></el-icon>
                    </el-tooltip>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="性别" prop="gender" class="form-field">
                <el-radio-group v-model="jobseekerForm.gender">
                  <el-radio label="male">男</el-radio>
                  <el-radio label="female">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="年龄" prop="age" class="form-field">
                <el-input-number v-model="jobseekerForm.age" :min="18" :max="60" />
              </el-form-item>
              <el-form-item label="手机号码" prop="phone" class="form-field">
                <el-input v-model="jobseekerForm.phone" />
              </el-form-item>
            </div>

            <el-form-item label="电子邮箱" prop="email" class="form-field">
              <el-input v-model="jobseekerForm.email" />
            </el-form-item>
          </div>

          <div class="form-group">
            <h4 class="form-section-title">求职信息</h4>
            <div class="form-row">
              <el-form-item label="学历" prop="education" class="form-field">
                <el-select v-model="jobseekerForm.education" placeholder="请选择">
                  <el-option label="高中" value="high" />
                  <el-option label="专科" value="college" />
                  <el-option label="本科" value="bachelor" />
                  <el-option label="硕士" value="master" />
                  <el-option label="博士" value="doctor" />
                </el-select>
              </el-form-item>
              <el-form-item label="工作经验" prop="hasExperience" class="form-field">
                <el-radio-group v-model="jobseekerForm.hasExperience">
                  <el-radio :label="1">有</el-radio>
                  <el-radio :label="0">无</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="期望薪资" prop="salaryRange" class="form-field">
                <div class="salary-range">
                  <el-input-number v-model="jobseekerForm.salaryWishK" />
                  千/月
                </div>
              </el-form-item>
              <el-form-item label="居住地址" prop="address" class="form-field">
                <el-input v-model="jobseekerForm.address" />
              </el-form-item>
            </div>

            <el-form-item label="个人介绍" prop="introduction" class="form-field">
              <el-input
                v-model="jobseekerForm.introduction"
                type="textarea"
                :rows="4"
              />
            </el-form-item>
          </div>
        </div>

        <div class="form-actions">
          <el-button type="primary" native-type="submit" class="submit-button">
            注册
          </el-button>
        </div>
      </el-form>

      <!-- 企业表单 -->
      <el-form
        v-if="userType === 'company'"
        ref="companyFormRef"
        :model="companyForm"
        :rules="companyRules"
        @submit.prevent="handleSubmit"
        label-position="top"
        class="register-form"
      >
        <div class="form-group">
          <el-form-item label="企业账户名" prop="username" class="form-field">
            <el-input v-model="companyForm.username" />
          </el-form-item>

          <el-form-item label="企业名称" prop="companyName" class="form-field">
            <el-input v-model="companyForm.companyName" />
          </el-form-item>

          <el-form-item label="密码" prop="password" class="form-field">
            <el-input
              v-model="companyForm.password"
              show-password
              type="password"
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword" class="form-field">
            <el-input
              v-model="companyForm.confirmPassword"
              show-password
              type="password"
            />
          </el-form-item>

          <el-form-item label="企业介绍" prop="companyIntroduction" class="form-field">
            <el-input
              v-model="companyForm.companyIntroduction"
              type="textarea"
              :rows="4"
            />
          </el-form-item>
        </div>

        <div class="form-actions">
          <el-button type="primary" native-type="submit" class="submit-button">
            注册
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import {
  User,
  OfficeBuilding,
  InfoFilled
} from '@element-plus/icons-vue';
import { addCompany, addEmp, addLogin } from '@/api/register.ts'
import type {LoginerData} from '@/api/register.ts'
import router from '@/router'
import {setAuthStatus} from '@/utils/auth.ts'
import type {EmpData, CompanyData} from '@/api/register.ts'

// 用户类型
type UserType = 'jobseeker' | 'company';

// 求职者表单类型
interface JobseekerForm {
  username: string;
  nickname: string;
  password: string;
  confirmPassword: string;
  realName: string;
  gender: string;
  age: number;
  phone: string;
  email: string;
  education: string;
  hasExperience: number;
  salaryWishK: number;
  address: string;
  introduction: string;
}

// 企业表单类型
interface CompanyForm {
  username: string;
  companyName: string;
  password: string;
  confirmPassword: string;
  companyIntroduction: string;
}

const userType = ref<UserType>('jobseeker');
const jobseekerFormRef = ref<FormInstance>();
const companyFormRef = ref<FormInstance>();

const jobseekerForm = ref<JobseekerForm>({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: '',
  realName: '',
  gender: '',
  age: 18,
  phone: '',
  email: '',
  education: '',
  hasExperience: 0,
  salaryWishK: 0,
  address: '',
  introduction: ''
});

const companyForm = ref<CompanyForm>({
  username: '',
  companyName: '',
  password: '',
  confirmPassword: '',
  companyIntroduction: '',
});

const requestData = ref<LoginerData>({
  username: '',
  password: '',
  role: 0,
})

// 密码验证函数
const validatePassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (value.length < 6) {
    callback(new Error('密码长度不能少于6位'));
  } else {
    callback();
  }
};

// 确认密码验证函数
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  const form = userType.value === 'jobseeker' ? jobseekerForm.value : companyForm.value;
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

// 求职者表单验证规则
const jobseekerRules: FormRules<JobseekerForm> = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
};

// 企业表单验证规则
const companyRules: FormRules<CompanyForm> = {
  username: [
    { required: true, message: '请输入企业账户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  companyName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

// 切换用户类型
const handleUserTypeChange = () => {
  if (userType.value === 'jobseeker') {
    // 重置求职者表单
    jobseekerForm.value = {
      username: '',
      nickname: '',
      password: '',
      confirmPassword: '',
      realName: '',
      gender: '',
      age: 18,
      phone: '',
      email: '',
      education: '',
      hasExperience: 0,
      salaryWishK: 0,
      address: '',
      introduction: ''
    };
  } else {
    // 重置企业表单
    companyForm.value = {
      username: '',
      companyName: '',
      password: '',
      confirmPassword: '',
      companyIntroduction: ''
    };
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    if (userType.value === 'jobseeker') {
      await jobseekerFormRef.value?.validate();
      requestData.value.role = 0;
      requestData.value.password = jobseekerForm.value.password;
      requestData.value.username = jobseekerForm.value.username;
      console.log(requestData.value);
      await addLogin(requestData.value);
      const empData = ref<EmpData>({
        username: jobseekerForm.value.username,
        nickname: jobseekerForm.value.nickname,
        password: jobseekerForm.value.password,
        name: jobseekerForm.value.realName,
        age: jobseekerForm.value.age,
        salaryWishK: jobseekerForm.value.salaryWishK,
        address: jobseekerForm.value.address,
        hasExperience: jobseekerForm.value.hasExperience,
        phone: jobseekerForm.value.phone,
        email: jobseekerForm.value.email,
        eduBack: jobseekerForm.value.education,
        introduction: jobseekerForm.value.introduction,
        sex: (jobseekerForm.value.gender === '男'? 1:0),
      })
      await addEmp(empData.value);
      setAuthStatus(true ,requestData.value.username)
      await  router.push('/job_seeker_home');
      console.log('求职者注册信息：', jobseekerForm.value);
    } else {
      await companyFormRef.value?.validate();
      requestData.value.role = 1;
      requestData.value.password = companyForm.value.password;
      requestData.value.username = companyForm.value.username;
      await addLogin(requestData.value);
      const companyData = ref<CompanyData> ({
        username: companyForm.value.username,
        nickName: companyForm.value.companyName,
        password: companyForm.value.password,
        companyIntroduction: companyForm.value.companyIntroduction,
      })
      await addCompany(companyData.value);
      setAuthStatus(true ,requestData.value.username)
      await router.push('/company_home');
      console.log('企业注册信息：', companyForm.value);
    }
  } catch (error) {
    console.log('表单验证失败', error);
  }
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.register-box {
  width: 100%;
  max-width: 800px;
}

.register-header {
  text-align: center;
  margin-bottom: 24px;
}

.register-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 0;
}

.user-type-selector {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.user-type-button {
  width: 200px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-type-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-type-icon {
  font-size: 36px;
  margin-bottom: 8px;
}

.user-type-description {
  text-align: center;
  color: #909399;
  margin-bottom: 24px;
}

.register-form {
  padding: 0 20px;
}

.form-section {
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 24px;
}

.form-section-title {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  font-weight: 500;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-field {
  margin-bottom: 18px;
}

.salary-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.submit-button {
  width: 200px;
}
</style>